<?php
namespace app\api\controller;

use \think\Controller;
use \think\Db;
class Order extends Base
{

    /**
     * 我的购物车
     */
    public function myCar(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['car_userid'] = $user_id;
        $where['car_status'] = 1;
        //1、先分组商家，取得分组数据
        $data = Db::table('up_shopping_car')->alias('car')
            ->join('up_shops s','car.car_shopid=s.s_id','LEFT')
            ->where($where)
            ->where('s_status',1)//正常的商户
            ->order('car_time DESC')
            ->group('car_shopid')
//            ->field('')
            ->page($page,5)
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['manjian'] = 1;//1是不满减
                //-----------------
                $today = date('Y-m-d');
                $mjyh = Db::table('up_shop_active')
                    ->where('sa_shopid',$v['car_shopid'])
                    ->where('sa_start','<=',$today)
                    ->where('sa_end','>=',$today)
                    ->find();
                if($mjyh){
                    $data[$k]['manjian'] = 2;//2是满减
                    $data[$k]['manjian_rule'] = $mjyh['sa_rule'];//规则
                    $data[$k]['manjian_rule_str'] = $mjyh['sa_rule_con'];//规则字符串
                }
                //-----------------
                $where['car_shopid'] = $v['car_shopid'];
                //商品必须存在
                $where['g_status'] = 1;
                $where['g_id'] = array('>',0);
                //TODO
                $goods = Db::table('up_shopping_car')->alias('car')
                    ->join('up_goods g','car.car_goodid=g.g_id','LEFT')
                    ->where($where)
                    ->order('car_time DESC')
                    ->select();
                if(!$goods){
                    unset($data[$k]);
                }else{
                    $data[$k]['goods'] = $goods;
                }
            }
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 删除一个购物车
     */
    public function deleteMyCar(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $car = Db::table('up_shopping_car')->where('car_id',$car_id)->find();
        $res = Db::table('up_shopping_car')
            ->where('car_userid',$car['car_userid'])
            ->where('car_shopid',$car['car_shopid'])
            ->delete();
        if($res){
            return json_encode(['status'=>200,'msg'=>'ok']);
        }else{
            return json_encode(['status'=>0,'msg'=>'删除失败']);
        }

    }
    /**
     * 确认订单页1——确认
     * 购物车的id集合:carids
     * 收货地址id:add_id
     * 备注:remark（怎么传值）
     * 那方支付：type（1是支付宝  2是微信）
     */
    public function sureOrder(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //---------------结合下这几个判断-------------------------
        $today = date('Y-m-d');
        $where = array();
        $where['car_userid'] = $user_id;
        $where['car_status'] = 1;
        $where['car_shopid'] = $shopid;
        //商品必须存在
        $where['g_status'] = 1;
        $where['g_id'] = array('>',0);
        //1、先分组商家，取得分组数据
        $shop = Db::table('up_shops')
            ->where('s_id',$shopid)
            ->find();
        $goods = Db::table('up_shopping_car')->alias('car')
            ->join('up_goods g','car.car_goodid=g.g_id','LEFT')
            ->where($where)
            ->select();
        $data = array();
        $packfei = 0;//1、、、包装费
        $allmoney = 0;//2、、、所有商品金额
        $manjian = 0;//3-1、、、满减的判断依据（非秒杀商品的金额）
        foreach ($goods as $k2 => $v2) {
            $packfei += $v2['g_pack'] * $v2['car_number'];//包装费
            if ($v2['g_prcie_kill'] != 0 && $v2['g_kill_start'] <= $today && $v2['g_kill_end'] >= $today) {
                $allmoney += $v2['g_prcie_kill'] * $v2['car_number'];//秒杀价
            } else {
                $allmoney += $v2['g_price_now'] * $v2['car_number'];//非秒杀的价格
                $manjian += $v2['g_price_now'] * $v2['car_number'];//非秒杀时满减的判断依据
            }
        }
        $post = 0;//4、、、邮费
        if ($allmoney < $shop['s_mianyou']) {
            $post = $shop['s_post'];//配送费就是邮费
        }
        //满减信息计算
        $manjianMoney = 0;//3-2、、、满减了多少
        $mjyh = Db::table('up_shop_active')
            ->where('sa_shopid', $shop['s_id'])
            ->where('sa_start', '<=', $today)
            ->where('sa_end', '>=', $today)
            ->find();
        if ($mjyh) {
            $rule = trim($mjyh['sa_rule'], ',');//规则
            $rule_arr = explode(',', $rule);
            foreach ($rule_arr as $vv) {
                $vv_arr = explode('-', $vv);
                if ($manjian >= $vv_arr[0]) {
                    $manjianMoney = $vv_arr[1];
                }
            }

        }
        $pay = $allmoney + $packfei + $post - $manjianMoney;
        $data['allmoney'] = $allmoney;//商品总额
        $data['packfei'] = $packfei;//包装费
        $data['post'] = $post;//配送费
        $data['manjianMoney'] = $manjianMoney;//优惠金额
        $data['pay'] = $pay;//用户实际支付金额
        return json_encode(['status'=>200,'shop'=>$shop,'goods'=>$goods,'data'=>$data]);
    }

    /**
     * 获取附近的符合的收货地址
     * lat  lon
     * @return string
     */
    public function getNearAddress()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['add_userid'] = $user_id;
        $mile = Db::table('up_set_juli')->where('juli_id',2)->value('juli_value');
        $miles = $mile*1000;
        $field = 'add_id,add_lat,add_lon,add_phone,add_address,add_username,add_sex,add_type';
        $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - add_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(add_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - add_lon * PI() / 180) / 2),2))) * 1000) AS distance';
        $data = Db::table('up_user_address')
            ->field($field)
            ->where($where)
            ->having("distance <= $miles")
            ->order('add_type DESC,distance ASC')
//            ->page($page,15)
            ->select();
        return json_encode(['status'=>200,'data'=>$data]);
    }

    /**
     * 确认订单页2——支付
     * 收货地址id:add_id
     * 备注:remark（怎么传值）
     * 那方支付：type（1是支付宝  2是微信）
     */
    public function makeOrder(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $number = date('YmdHis') . rand(1000000,9999999);
        //1、先分组商家，取得分组数据
        $shop = Db::table('up_shops')
            ->where('s_id',$shopid)
            ->find();
        if($shop['s_status'] != 1){
            return json_encode(['status'=>0,'msgsss'=>'此店铺今天不营业']);
        }
        if($shop['s_admin'] != 1){
            return json_encode(['status'=>0,'msgsss'=>'此店铺已被关停']);
        }
        $today = date('Y-m-d');
        Db::startTrans();
        try{
            $orderId = Db::table('up_order')->insertGetId(['order_userid' => $user_id]);
            //---------------结合下这几个判断-------------------------
            $where = array();
            $where['car_userid'] = $user_id;
            $where['car_status'] = 1;
            $where['car_shopid'] = $shopid;
            //商品必须存在
            $where['g_status'] = 1;
            $where['g_id'] = array('>', 0);
            //---------------------end------------------
            $goods = Db::table('up_shopping_car')->alias('car')
                ->join('up_goods g', 'car.car_goodid=g.g_id', 'LEFT')
                ->where($where)
                ->select();
            $allmoney = 0;
            $manjian = 0;
            $packfei = 0;
            $allcount = 0;
            $order = array();
            foreach ($goods as $k2 => $v2) {
                //1、首先是不是可买份数变了
                if ($v2['g_canbuy'] != 0 && $v2['g_canbuy'] > 0) {
                    if ($v2['car_number'] > $v2['g_canbuy']) {
                        return json_encode(['status' => 0, 'msg' => '商品' . $v2['g_name'] . '限制购买' . $v2['g_canbuy'] . '份']);
                    }
                }
                //3、入info
                $oi = array();
                $oi['oi_order_id'] = $orderId;
                //2、价格(包装费，总价，满减价参考)
                $packfei += $v2['g_pack'] * $v2['car_number'];//包装费
                $allcount += $v2['car_number'];//所买商品的数量

                if ($v2['g_prcie_kill'] != 0 && $v2['g_kill_start'] <= $today && $v2['g_kill_end'] >= $today) {
                    $allmoney += $v2['g_prcie_kill'] * $v2['car_number'];//秒杀价
                    $oi['oi_price_kill'] = $v2['g_prcie_kill'];//详情的秒杀判断
                } else {
                    $allmoney += $v2['g_price_now'] * $v2['car_number'];//非秒杀的价格
                    $manjian += $v2['g_price_now'] * $v2['car_number'];//非秒杀时满减的判断依据
                }
                //------------减库存
                if($v2['g_stock'] != -1){
                    if($v2['g_stock'] >= $v2['car_number']){
                        Db::table('up_goods')
                            ->where('g_id',$v2['g_id'])
                            ->setDec('g_stock',$v2['car_number']);
                    }else{
                        return json_encode(['status'=>0,'msg'=>'库存不足']);
                    }

                }
                //------------------
                //3、入info
                $oi['oi_good_id'] = $v2['g_id'];
                $oi['oi_shop_id'] = $v2['g_shop'];
                $oi['oi_price_before'] = $v2['g_price_before'];
                $oi['oi_price_now'] = $v2['g_price_now'];
                $oi['oi_num'] = $v2['car_number'];
                $oi['oi_good_name'] = $v2['g_name'];
                $oi['oi_good_thumb'] = $v2['g_thumb'];
                $oi['oi_good_pack'] = $v2['g_pack'];
                Db::table('up_order_info')->insertGetId($oi);
                Db::table('up_shopping_car')->where('car_id',$v2['car_id'])->delete();
            }
            $order['order_number'] = $number;
            $order['order_userid'] = $user_id;
            $order['order_num'] = $allcount;
            $order['order_shopid'] = $shopid;
            //收件人信息
            $address = Db::table('up_user_address')
                ->where('add_id', $add_id)
                ->find();
            $order['order_address_sex'] = $address['add_sex'];
            $order['order_address'] = $address['add_address'];
            $order['order_address_phone'] = $address['add_phone'];
            $order['order_address_name'] = $address['add_username'];
            //============
            $post = 0;
            $order['order_money_all'] = $allmoney;
            if ($allmoney < $shop['s_mianyou']) {
                $order['order_money_send'] = $shop['s_post'];//配送费就是邮费
                $post = $shop['s_post'];//配送费就是邮费
            }
            $order['order_money_pack'] = $packfei;
            //满减信息计算
            $order['order_money_man'] = 0;
            $mjyh = Db::table('up_shop_active')
                ->where('sa_shopid', $shop['s_id'])
                ->where('sa_start', '<=', $today)
                ->where('sa_end', '>=', $today)
                ->find();
            if ($mjyh) {
                $rule = trim($mjyh['sa_rule'], ',');//规则
                $rule_arr = explode(',', $rule);
                foreach ($rule_arr as $vv) {
                    $vv_arr = explode('-', $vv);
                    if ($manjian >= $vv_arr[0]) {
                        $order['order_money_man'] = $vv_arr[1];
                    }
                }

            }
            //满减信息计算end
            $order['order_remark'] = $remark;
            $order['order_type'] = $type;
            $order['order_time'] = date('Y-m-d H:i:s');
            $order['order_user_pay'] = $allmoney + $packfei + $post - $order['order_money_man'];
            Db::table('up_order')->where('order_id', $orderId)->update($order);
            $pay = $order['order_user_pay'];
            Db::commit();
            if($type == 1){
                $respont = $this->getParam($number,'0.01');
                return json_encode($respont);
            }else{
                $orderWx = array();
                $orderWx['body'] = '红集';
                $orderWx['total_fee'] = 1;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'APP';
                $respont = $this->WeChatPayReady($orderWx);
                return json_encode(['status'=>200,'msgsss'=>$respont]);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msgsss'=>'生成订单失败，请联系管理员']);
        }
    }
     /**
     * 确认订单页 TODO：这是之前的算法，留待备用
     * 购物车的id集合:carids
     * 收货地址id:add_id
     * 备注:remark（怎么传值）
     * 那方支付：type（1是支付宝  2是微信）
     */
//    public function makeOrder(){
//        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            $returnData['status'] = 301;
//            $returnData['msg'] = "Token失效！请重新登录！";
//            return json_encode($returnData);
//        }
//        $number = date('YmdHis') . rand(1000000,9999999);
//        $where = array();
//        $where['car_id'] = array('in',$carids);
//        //1、先分组商家，取得分组数据
//        $data = Db::table('up_shopping_car')->alias('car')
//            ->join('up_shops s','car.car_shopid=s.s_id','LEFT')
//            ->where($where)
//            ->group('car_shopid')
//            ->select();
//        $today = date('Y-m-d');
//        $pay = 0;
//        Db::startTrans();
//        try{
//            foreach ($data as $k=>$v){//这里有店铺活动
//                $orderId = Db::table('up_order')->insertGetId(['order_userid'=>$user_id]);
//                $where['car_shopid'] = $v['car_shopid'];
//                $goods = Db::table('up_shopping_car')->alias('car')
//                    ->join('up_goods g','car.car_goodid=g.g_id','LEFT')
//                    ->where($where)
//                    ->select();
//                $allmoney = 0;
//                $manjian = 0;
//                $packfei = 0;
//                $allcount = 0;
//                $order = array();
//                foreach ($goods as $k2=>$v2){
//                    //1、首先是不是可买份数变了
//                    if($v2['g_canbuy'] != 0 && $v2['g_canbuy'] > 0){
//                        if($v2['car_number']>$v2['g_canbuy']){
//                            return json_encode(['status'=>0,'msg'=>'商品' . $v2['g_name'] . '限制购买' . $v2['g_canbuy'] . '份']);
//                        }
//                    }
//                    //3、入info
//                    $oi = array();
//                    $oi['oi_order_id'] = $orderId;
//                    //2、价格(包装费，总价，满减价参考)
//                    $packfei += $v2['g_pack']*$v2['car_number'];//包装费
//                    $allcount += $v2['car_number'];//所买商品的数量
//
//                    if($v2['g_prcie_kill'] != 0 && $v2['g_kill_start']<=$today && $v2['g_kill_end']>=$today){
//                        $allmoney += $v2['g_prcie_kill']*$v2['car_number'];//秒杀价
//                        $oi['oi_price_kill'] = $v2['g_prcie_kill'];//详情的秒杀判断
//                    }else{
//                        $allmoney += $v2['g_price_now']*$v2['car_number'];//非秒杀的价格
//                        $manjian += $v2['g_price_now']*$v2['car_number'];//非秒杀时满减的判断依据
//                    }
//                    //3、入info
//                    $oi['oi_good_id'] = $v2['g_id'];
//                    $oi['oi_shop_id'] = $v2['g_shop'];
//                    $oi['oi_price_before'] = $v2['g_price_before'];
//                    $oi['oi_price_now'] = $v2['g_price_now'];
//                    $oi['oi_num'] = $v2['car_number'];
//                    $oi['oi_good_name'] = $v2['g_name'];
//                    $oi['oi_good_thumb'] = $v2['g_thumb'];
//                    $oi['oi_good_pack'] = $v2['g_pack'];
//                    Db::table('up_order_info')->insertGetId($oi);
//                }
//                $order['order_number'] = $number;
//                $order['order_userid'] = $user_id;
//                $order['order_num'] = $allcount;
//                $order['order_shopid'] = $v['car_shopid'];
//                //收件人信息
//                $address = Db::table('up_user_address')
//                    ->where('add_id',$add_id)
//                    ->find();
//                $order['order_sheng'] = $address['add_sheng'];
//                $order['order_shi'] = $address['add_shi'];
//                $order['order_qu'] = $address['add_qu'];
//                $order['order_address_sex'] = $address['add_sex'];
//                $order['order_address'] = $address['add_address'];
//                $order['order_address_phone'] = $address['add_phone'];
//                $order['order_address_name'] = $address['add_username'];
//                //============
//                $post = 0;
//                $order['order_money_all'] = $allmoney;
//                if($allmoney < $v['s_mianyou']){
//                    $order['order_money_send'] = $v['s_post'];//配送费就是邮费
//                    $post = $v['s_post'];//配送费就是邮费
//                }
//                $order['order_money_pack'] = $packfei;
//                //满减信息计算
//                $order['order_money_man'] = 0;
//                $mjyh = Db::table('up_shop_active')
//                    ->where('sa_shopid',$v['car_shopid'])
//                    ->where('sa_start','<=',$today)
//                    ->where('sa_end','>=',$today)
//                    ->find();
//                if($mjyh){
//                    $rule = trim($mjyh['sa_rule'],',');//规则
//                    $rule_arr = explode(',',$rule);
//                    foreach ($rule_arr as $vv){
//                        $vv_arr = explode('-',$vv);
//                        if($manjian >= $vv_arr[0]){
//                            $order['order_money_man'] = $vv_arr[1];
//                        }
//                    }
//
//                }
//                //满减信息计算end
//                $order['order_remark'] = $remark;// 商量一下怎么给
//                $order['order_type'] = $type;
//                $order['order_time'] = date('Y-m-d H:i:s');
//                $order['order_user_pay'] = $allmoney+$packfei+$post-$order['order_money_man'];
//                Db::table('up_order')->where('order_id',$orderId)->update($order);
//                $pay += $order['order_user_pay'];
//            }
//            Db::commit();
//            $respont = $this->getParam($number,$pay);
//            return json_encode($respont);
//        }catch (\Exception $e) {
//            Db::rollback();
//            return json_encode(['status'=>0,'msg'=>'生成订单失败，请联系管理员']);
//        }
//    }

    /**
     * 单独为取消订单做的支付
     * @return string
     */
    public function onlyPay()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $order = array();
        $number = date('YmdHis') . rand(1000000, 9999999);
        $order['order_number'] = $number;
        $order['order_type'] = $type;
        $pay = Db::table('up_order')->where('order_id', $order_id)->value('order_user_pay');
        $res = Db::table('up_order')->where('order_id', $order_id)->update($order);
        if($res){
            if($type == 1){
                $respont = $this->getParam($number,'0.01');
                return json_encode($respont);
            }else{
                $orderWx = array();
                $orderWx['body'] = '红集';
                $orderWx['total_fee'] = 1;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'APP';
                $respont = $this->WeChatPayReady($orderWx);
                return json_encode(['status'=>200,'msgsss'=>$respont]);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'订单号更改失败']);
        }

    }
    /**
     * 支付回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo){
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED'){
                $number = $getInfo['out_trade_no'];
                $transaction_id = $getInfo['trade_no'];
                $paytime = $getInfo['gmt_payment'];
                if($this->doneOrder($number,$transaction_id,$paytime)){
                    //通知和推送
                    $shopid = Db::table('up_order')->where('order_number', $number)->value('order_shopid');
//                    allInNotice('您有新的订单','您有新的订单，请注意查收',$shopid);
                    try {
                        sendJpush("$shopid", '您有新的订单，请注意查收', array('a' => 'b'), 2, 100, 2);
                    } catch (\Exception $e) {
                    }
                    die('success');
                }else{
                    return 'error';
                }
            }
        }
    }
    public function huidiaoWx()
    {
        $xml=file_get_contents('php://input', 'r');
        $getInfo=$this->toArray($xml);
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign = $this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            $number = $getInfo['out_trade_no'];
            $transaction_id = $getInfo['transaction_id'];
            $paytime = $this->getDateBytimeDate("{$getInfo['time_end']}");
            if ($this->doneOrder($number, $transaction_id, $paytime)) {
                //通知和推送
                $shopid = Db::table('up_order')->where('order_number', $number)->value('order_shopid');
//                allInNotice('您有新的订单','您有新的订单，请注意查收',$shopid);
                try {
                    sendJpush("$shopid", '您有新的订单，请注意查收', array('a' => 'b'), 2, 100, 2);
                } catch (\Exception $e) {
                }
                $result = $getInfo;
            } else {
                $result = false;
            }
        }else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }
    public function doneOrder($number,$transaction_id,$paytime)
    {
        Db::startTrans();
        try{
            $order = Db::table('up_order')->where('order_number', $number)->find();
            //1、支付成功改状态
            $update = array();
            $update['order_status'] = 2;
            $update['order_back_transaction_id'] = $transaction_id;
            $update['order_paytime'] = $paytime;
            $update['order_paydate'] = substr($paytime,0,10);
            Db::table('up_order')
                ->where('order_number', $number)
                ->update($update);
            //1-2、改详情的时间及商品销量
            $orderid = $order['order_id'];
            Db::table('up_order_info')
                ->where('oi_order_id', $orderid)
                ->update(['oi_pay_time'=>$paytime]);
            //1-2、改详情的时间及商品销量
            $gids = Db::table('up_order_info')
                ->where('oi_order_id', $orderid)
                ->field('oi_good_id,oi_num')
                ->select();
            foreach ($gids as $k=>$v){
                Db::table('up_goods')
                    ->where('g_id', $v['oi_good_id'])
                    ->setInc('g_sale_num',$v['oi_num']);
            }
            //2、商户改余额
            Db::table('up_shops')
                ->where('s_id', $order['order_shopid'])
                ->setInc('s_money',$order['order_user_pay']);
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            return false;
        }

    }

    /**
     * 申请退款
     * @return string
     */
    public function tuikuan()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_order')
            ->where('order_id',$order_id)
            ->update(['order_in_out'=>2]);
        if($res){
            //给商户推送
            $shop_id = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            try {
                sendJpush("$shop_id", '您有新的配送订单，请注意查收', array('a' => 'b'), 2, 101, 2);
            } catch(\Exception $e) {

            }
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }

    /**
     * 投诉订单
     * @return string
     */
    public function tousu()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $can = Db::table('up_order')->where('order_id',$order_id)->value('order_tousu');
        if($can == 2){
            return json_encode(['status'=>0,'msg'=>'您已经投诉过了']);
        }
        Db::startTrans();
        try{
            Db::table('up_order')
                ->where('order_id',$order_id)
                ->update(['order_tousu'=>2,'order_tousu_reason'=>$reason]);
            //1、商户减分
            $sid = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            Db::table('up_shops')->where('s_id',$sid)->setDec('s_integral',5);
            $nowfen = Db::table('up_shops')->where('s_id',$sid)->value('s_integral');
            allInJifen('订单投诉：'.$reason,2,5,$sid);
            if($nowfen <= 0){
                Db::table('up_shops')->where('s_id',$sid)->update(['s_status'=>2]);
            }
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 我的各种订单的数量
     * name,avatar
     */
    public function myOrderNum()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $this->updateOneToDel($user_id);
        $data['noPay'] = Db::table('up_order')
            ->where('order_userid', $user_id)
            ->where('order_status', 1)
            ->where('order_in_out', 1)
            ->count();
        $data['havePay'] = Db::table('up_order')
            ->where('order_userid', $user_id)
            ->where('order_status', 2)
            ->where('order_in_out', 1)
            ->count();
        $data['noComment'] = Db::table('up_order')
            ->where('order_userid', $user_id)
            ->where('order_status', 3)
            ->where('order_in_out', 1)
            ->count();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     *  TODO 将我的未支付的订单删掉并且库存改回去
     * param $user_id
     */
    public function updateOneToDel($user_id)
    {
        $today = date('Y-m-d H:i:s');
        $deltime = date("Y-m-d H:i:s",(strtotime("{$today}")-1800));
        $order = Db::table('up_order')
            ->where('order_userid',$user_id)
            ->where('order_status',1)
            ->where('order_time','<=',$deltime)
            ->column('order_id');
        if($order){
            foreach ($order as $v){
                $infos = Db::table('up_order_info')->alias('o')
                    ->join('up_goods g','o.oi_good_id=g.g_id','LEFT')
                    ->where('oi_order_id',$v)
                    ->field('g_stock,g_id,oi_num')
                    ->select();
                //------------TODO 加库存
                foreach ($infos as $v2){
                    if($v2['g_stock'] != -1){
                        Db::table('up_goods')
                            ->where('g_id',$v2['g_id'])
                            ->setInc('g_stock',$v2['oi_num']);
                    }
                }
                //------------------
            }
            Db::table('up_order')
                ->where('order_id','in',$order)
                ->delete();
        }
        return true;
    }
    /**
     * 我的不同类型的订单(也可当详情用)
     * type(0全部  1待支付  2待收货  3是已收货  4是已完成)
     * @return string
     */
    public function myOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //---------------------------------------------
        $this->updateOneToDel($user_id);
        //-----------------------------------------------
        $where = array();
        $where['order_userid'] = $user_id;
//        $where['order_in_out'] = 1;//不含退款的
        if($type > 0){
            if($type == 5){
                $where['order_in_out'] = array('>',1);
            }else{
                $where['order_status'] = $type;
                $where['order_in_out'] = 1;
            }
        }
        $order = Db::table('up_order')->alias('o')
            ->join('up_shops s','o.order_shopid=s.s_id','LEFT')
            ->where($where)
            ->field('o.*,s.s_id,s.s_name,s_thumb')
            ->order('order_time DESC')
            ->page($page,10)
            ->select();
        if($order){
            foreach ($order as $k=>$v){
                $order[$k]['goods'] = Db::table('up_order_info')
                    ->where('oi_order_id',$v['order_id'])
                    ->select();
            }
        }
        $time = time();
        return json_encode(['status'=>200,'msg'=>$order,'time'=>$time]);
    }
    /**
     * 订单详情
     * order_id
     * @return string
     */
    public function myOrderInfo()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['order_id'] = $order_id;
        $order = Db::table('up_order')->alias('o')
            ->join('up_shops s','o.order_shopid=s.s_id','LEFT')
            ->where($where)
            ->field('o.*,s.s_id,s.s_name,s_phone,s_thumb')
            ->find();
        $goods = Db::table('up_order_info')
            ->where('oi_order_id',$order_id)
            ->select();
        $time = time();
        return json_encode(['status'=>200,'order'=>$order,'goods'=>$goods,'time'=>$time]);
    }

    /**
     * 取消订单
     * order_id
     * @return string
     */
    public function cancelOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        Db::startTrans();
        try{
            Db::table('up_order')
                ->where('order_id',$order_id)
                ->delete();
            $goods = Db::table('up_order_info')->alias('oi')
                ->join('up_goods g', 'oi.oi_good_id=g.g_id', 'LEFT')
                ->where('oi_order_id',$order_id)
                ->select();
            foreach ($goods as $k=>$v){
                //------------减库存
                if($v['g_stock'] != -1){
                    Db::table('up_goods')
                        ->where('g_id',$v['oi_good_id'])
                        ->setInc('g_stock',$v['oi_num']);
                }
                //------------------
            }
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'取消成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 确认收货
     * order_id
     * @return string
     */
    public function getMyOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_order')
            ->where('order_id',$order_id)
            ->update(['order_status'=>3,'order_send_status'=>3,'order_driver_status'=>3]);
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 评价此订单
     * order_id
     * @return string
     */
    public function commentMyOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $have = Db::table('up_good_comment')->where('comment_order_id',$order_id)->find();
        if($have){
            return json_encode(['status'=>0,'msg'=>'您已经评价过了']);
        }
        Db::startTrans();
        try{
            Db::table('up_order')->where('order_id',$order_id)->update(['order_status'=>4]);
            $shid = Db::table('up_order')->where('order_id',$order_id)->value('order_shopid');
            $user = Db::table('up_u_user')->where('user_id',$user_id)
                ->field('user_username,user_image')->find();
            $goodids = Db::table('up_order_info')
                ->where('oi_order_id',$order_id)
                ->column('oi_good_id');
            $str = implode($goodids,',');
            $comment = array();
            $comment['comment_goodid'] = ','.$str.',';
            $comment['comment_shopid'] = $shid;
            $comment['comment_user_id'] = $user_id;
            $comment['comment_score'] = $score;
            $comment['comment_content'] = $content;
            $comment['comment_time'] = date('Y-m-d H:i:s');
            $comment['comment_order_id'] = $order_id;
            $comment['comment_username'] = $user['user_username'];
            $comment['comment_image'] = $user['user_image'];
            Db::table('up_good_comment')->insert($comment);
            //1、商品的评分和人数修改
            foreach ($goodids as $v){
                $scoredata = Db::table('up_goods')->where('g_id',$v)->field('g_num,g_score')->find();
                $newscore = ($scoredata['g_num']*$scoredata['g_score']+$score)/($scoredata['g_num']+1);
                $goodscore = round($newscore,1);
                Db::table('up_goods')->where('g_id',$v)->update(['g_score'=>$goodscore]);
            }
            Db::table('up_goods')->where('g_id','in',$goodids)->setInc('g_num');
            //2、店铺的评分
            $shopnum = Db::table('up_good_comment')->where('comment_shopid',$shid)->count();
            $shopscore = Db::table('up_shops')->where('s_id',$shid)->value('s_score');
            $shopnewscroe = (($shopnum-1)*$shopscore+$score)/$shopnum;
            $nowscore = round($shopnewscroe,1);
            Db::table('up_shops')->where('s_id',$shid)->update(['s_score'=>$nowscore]);
            //3、评分低的话扣分
            if($score <= 3){
                //1、商户减分
                $jian_s = 4-$score;
                Db::table('up_shops')->where('s_id',$shid)->setDec('s_integral',$jian_s);
                $nowfen = Db::table('up_shops')->where('s_id',$shid)->value('s_integral');
                allInNotice('扣分通知','您有订单评价'.$score.'分，扣'.$jian_s.'分',$shid);
                allInJifen('订单评分'.$score.'分',2,$jian_s,$shid);
                if($nowfen <= 0){
                    Db::table('up_shops')->where('s_id',$shid)->update(['s_status'=>2]);
                }
            }
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }

}